package com.ehome.poct.core.dao.mybatis;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ehome.mybatisplus.support.AbstractCrudRepository;
import com.ehome.poct.core.api.dto.report.ConfConclusionDTO;
import com.ehome.poct.core.api.dto.report.CrpSaaConclusionDTO;
import com.ehome.poct.core.dao.entity.report.CrpSaaConclusionDO;
import com.ehome.poct.core.dao.mybatis.mapper.report.CrpSaaConclusionMapper;
import com.ehome.poct.core.repository.report.ConfConclusionRepository;
import com.ehome.poct.core.repository.report.CrpSaaConclusionRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.Optional;

/**
 * 三联测中crp-saa的结论分析配置RepositoryImpl
 *
 * @author wuyingchao
 * @Date 2022-05-20 10:39
 */
@Repository
@AllArgsConstructor
public class CrpSaaConclusionRepositoryImpl extends AbstractCrudRepository<CrpSaaConclusionDO, CrpSaaConclusionDTO> implements CrpSaaConclusionRepository {
    private final CrpSaaConclusionMapper mapper;
    private final ConfConclusionRepository conclusionRepository;

    @Override
    public ConfConclusionDTO getByValue(BigDecimal crp, BigDecimal saa, String code) {
        final var entity = mapper.selectOne(Wrappers.<CrpSaaConclusionDO>lambdaQuery()
                .le(CrpSaaConclusionDO::getCrpMin, crp).gt(CrpSaaConclusionDO::getCrpMax, crp)
                .le(CrpSaaConclusionDO::getSaaMin, saa).gt(CrpSaaConclusionDO::getSaaMax, saa)
                .eq(CrpSaaConclusionDO::getResultCode, code));
        // 匹配不到的情况，先返回其他类型
        return Optional.ofNullable(entity)
                .map(i -> conclusionRepository.selectOne(new ConfConclusionDTO().setCode(i.getConclusionCode())))
                .orElseGet(() -> conclusionRepository.selectOne(new ConfConclusionDTO().setCode(10)));
    }
}
